package com.health.mapp.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials;

public class UploadByOss {
	private static Log log = LogFactory.getLog(UploadByOss.class);
 
	
	
    public static PutObjectResult uploadByOss(File dst, String path) {

        log.fatal("uploadByOss start....................");
        String accessKeyId = PropertiesUtil.getString("oss.accessKeyId").trim();
        String accessKeySecret = PropertiesUtil.getString("oss.accessKeySecret").trim();
        String roleArn = PropertiesUtil.getString("oss.roleReadWrite").trim();
        String roleSessionName = PropertiesUtil.getString("oss.roleSessionName").trim();


        String policy = "{\n" +
                "	\"Version\": \"1\",\n" +
                "	\"Statement\": [\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "		    \"Action\": [\n" +
                "		    	\"oss:ListObjects\",\n" +
                "		    	\"oss:GetObject\"\n" +
                "		    ],\n" +
                "		    \"Resource\": [\n" +
                "		    	\"acs:oss:*:*:shouer\",\n" +
                "		   		\"acs:oss:*:*:shouer/*\"\n" +
                "		    ]\n" +
                "		},\n" +
                "		{\n" +
                "			\"Effect\": \"Allow\",\n" +
                "			\"Action\": [\n" +
                "				\"oss:AbortMultipartUpload\",\n" +
                "				\"oss:PutObject\"\n" +
                "			],\n" +
                "			\"Resource\": [\n" +
                "				\"acs:oss:*:*:shouer\",\n" +
                "				\"acs:oss:*:*:shouer/*\"\n" +
                "			]\n" +
                "		}\n" +
                "   ]\n" +
                "}";

        ProtocolType protocolType = ProtocolType.HTTPS;
        Credentials credentials = null;
        try {
            final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
                    roleArn, roleSessionName, policy, protocolType);

            if (null != response) {
                credentials = response.getCredentials();


                if (null != credentials) {

                    String bucketName = PropertiesUtil.getString("oss.bucketName").trim();
                    String endpoint = PropertiesUtil.getString("oss.endpoint").trim();

                    String accessKeyIdByToken = credentials.getAccessKeyId();
                    String accessKeySecretByToken = credentials.getAccessKeySecret();
                    String securityByToken = credentials.getSecurityToken();
                    OSSClient client = new OSSClient(endpoint, accessKeyIdByToken, accessKeySecretByToken, securityByToken);


                    InputStream content = null;
                    try {
                        content = new FileInputStream(dst);

                        ObjectMetadata meta = new ObjectMetadata();
                        meta.setContentLength(dst.length());

                        PutObjectResult result = client.putObject(bucketName, path, content, meta);
                        log.fatal(result);
                        client.shutdown();
                        return result;
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                } else {
                    log.fatal("credentials is " + credentials);
                }

            } else {

                log.fatal("response is " + response);

            }


        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }


        log.fatal("uploadByOss end....................");

        return null;
    }
	/**
	 * 
	 * 
	 * @param src src File
	 * @param dst  dst File
	 * @param ossSavePath  ossSavePath
	 * @throws Exception
	 */
	 public static void upload(File src, File dst,String ossSavePath) throws Exception{
		 
	        log.fatal("uploadByOss start....................");
	 		String accessKeyId = PropertiesUtil.getString("oss.accessKeyId").trim();
	 		String accessKeySecret = PropertiesUtil.getString("oss.accessKeySecret").trim();
			String roleArn = PropertiesUtil.getString("oss.roleReadWrite").trim();
		    String roleSessionName =  PropertiesUtil.getString("oss.roleSessionName").trim();
		    String bucketName =PropertiesUtil.getString("oss.bucketName").trim();
		   // String filepath=  PropertiesService.getString("ftp.upload.path")+"/"+DIR;
		    String endpoint= PropertiesUtil.getString("oss.endpoint").trim();

		   /* String accessKeyId = PropertiesService.getString("oss.accessKeyId").trim();
	 		String accessKeySecret = PropertiesService.getString("oss.accessKeySecret").trim();
			String roleArn = PropertiesService.getString("oss.roleWrite").trim();
		    String roleSessionName = PropertiesService.getString("oss.roleName").trim();
		    String bucketName =PropertiesService.getString("oss.bucketName").trim();
		   // String filepath=  PropertiesService.getString("ftp.upload.path")+"/"+DIR;
		    String endpoint= PropertiesService.getString("oss.endpoint").trim();*/
		    
			    
			    String policy="{\n"+
				  "	\"Version\": \"1\",\n"+
				  "	\"Statement\": [\n"+
				  "		{\n"+
				  "			\"Effect\": \"Allow\",\n"+
				  "		    \"Action\": [\n"+
				  "		    	\"oss:ListObjects\",\n"+
				  "		    	\"oss:GetObject\"\n"+
				  "		    ],\n"+
				  "		    \"Resource\": [\n"+
				  "		    	\"acs:oss:*:*:shouer\",\n"+
				  "		   		\"acs:oss:*:*:shouer/*\"\n"+
				  "		    ]\n"+
				  "		},\n"+
				  "		{\n"+
				  "			\"Effect\": \"Allow\",\n"+
				  "			\"Action\": [\n"+
				  "				\"oss:AbortMultipartUpload\",\n"+
				  "				\"oss:PutObject\"\n"+
				  "			],\n"+
				  "			\"Resource\": [\n"+
				  "				\"acs:oss:*:*:shouer\",\n"+
				  "				\"acs:oss:*:*:shouer/*\"\n"+
				  "			]\n"+
				  "		}\n"+
				  "   ]\n"+
				  "}";
			    ProtocolType protocolType = ProtocolType.HTTPS;
			    Credentials credentials = null;
			   
			      final AssumeRoleResponse response = assumeRole(accessKeyId, accessKeySecret,
			              roleArn, roleSessionName, policy, protocolType);
			      
			      if(null!=response)
			      {
			    	  credentials =  response.getCredentials();
			      
			      
			    	  if(null!=credentials)
			    	  {
			    		  String accessKeyIdByToken = credentials.getAccessKeyId();
					  	    String accessKeySecretByToken = credentials.getAccessKeySecret();
					  	    String securityByToken = credentials.getSecurityToken();
					        OSSClient client = new OSSClient(endpoint,accessKeyIdByToken,accessKeySecretByToken,securityByToken);
					        
					        
					        	  InputStream content = null;
								 
										content = new FileInputStream(dst);
										
										 // 创建上传Object的Metadata
									      ObjectMetadata meta = new ObjectMetadata();
									      // 必须设置ContentLength
									      meta.setContentLength(dst.length());
									      String key=ossSavePath;
									      
									  
									      log.fatal("key:"+key);
									      PutObjectResult result = client.putObject(bucketName, key, content, meta);
									      log.fatal("PutObjectResult getETag:"+result.getETag());
									      
			    		  
			    	  }
			    	  else
			    	  {
			    		  log.fatal("credentials is "+credentials);  
			    	  }
			    	
			      }
			      else
			      {
			    	  
			    	  log.fatal("response is "+response);  
			    	  
			      }
		      
			    log.fatal("uploadByOss end...................."); 
	 
	 }
	 static AssumeRoleResponse assumeRole(String accessKeyId,
				String accessKeySecret, String roleArn, String roleSessionName,
				String policy, ProtocolType protocolType) throws Exception {
				IClientProfile profile = DefaultProfile.getProfile(
						PropertiesUtil.getString("oss.region").trim(), accessKeyId, accessKeySecret);
				DefaultAcsClient client = new DefaultAcsClient(profile);

				final AssumeRoleRequest request = new AssumeRoleRequest();
				request.setVersion(PropertiesUtil.getString("oss.stsApiVersion").trim());
				request.setMethod(MethodType.POST);
				request.setProtocol(protocolType);

				request.setRoleArn(roleArn);
				request.setRoleSessionName(roleSessionName);
				request.setPolicy(policy);
				AssumeRoleResponse response =  client.getAcsResponse(request);
				return response;
	 }
}
